<?php

namespace App\Console\Commands;

use App\Jobs\ProcessDeleteData;
use App\Models\PushTask;
use App\Models\SalePlan;
use App\Models\SaleTask;
use App\Tools\Logs;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class DeleteData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'delete:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 查询三月份以前的计划
        $end_time = strtotime('-65 days');
        $maxId = SalePlan::where('end_time', '<=', $end_time)->whereNotNull('end_time')->orderByRaw('end_time - id desc')->value('id');
        $planResult = SalePlan::where('id', '<', $maxId)->limit(30)->get();

        foreach ($planResult as $value) {
            if (Redis::exists("plan_code_list")) {
                $dispatch_task_code = json_decode(Redis::get("plan_code_list"), true);
            }else{
                $dispatch_task_code = [];
            }

            if (in_array($value->plan_code, $dispatch_task_code)) {
                Logs::info("有任务跳过", [$value->plan_code], 'delete_'.date('Ymd'));
                continue;
            }else{
                $dispatch_task_code[] = $value->plan_code;
                Redis::set('plan_code_list', json_encode($dispatch_task_code));
            }

            ProcessDeleteData::dispatch($value->toArray());
        }
    }
}
